﻿(function ($) {
    $.fn.imgresize = function () {
        $(this).each(function () {
            var thisWidth = $(this).width();
            var thisHeight = $(this).height();
            var img = $("img", $(this));
            img.each(function () {

                $(this).load(function () {
                    
                    var childImgWidth = img.width();
                    var childImgHeight = img.height();
                    SetResize(thisHeight, thisWidth, childImgHeight,
                            childImgWidth, img);
                });
                $(this).each(function() {
					if (this.complete) {
						$(this).trigger('load');
					}
				});
            });
        });
    }

    function SetResize(divHeight, divWidth, imgHeight, imgWidth, img) {

        var c = divHeight - imgHeight;
        var d = divWidth - imgWidth;


        if (divHeight == imgHeight && divWidth == imgWidth) {
            //完全一致
            img.css("height", imgHeight);
            img.css("width", imgWidth);
        }

        if (divHeight >= imgHeight && divWidth >= imgWidth) {
            //div完全包括img

            img.css("height", imgHeight);
            img.css("margin-left", (d / 2) + "px");
            img.css("margin-top", (c / 2) + "px");
        } else if (divHeight < imgHeight && divWidth < imgWidth) {
            //img 完全超出div
            //根据宽高比  如果图片的宽高比 > div的宽高比 按高度压缩
            var divScale = divWidth / divHeight;
            var imgScale = imgWidth / imgHeight;


            if (imgScale >= divScale) {


                img.css("height", divHeight);
                var d = img.width() - divWidth;
                //保证居中
                img.css("margin-left", (-(d / 2)) + "px");

            } else {

                img.css("width", divWidth);
                //保证居中

                var c = img.height() - divHeight;
                //alert(imgHeight * yScale + "   " + divHeight);
                img.css("margin-top", (-(c / 2)) + "px");


            }

        } else if (divHeight >= imgHeight && divWidth < imgWidth) {
            //div的高度大于等于图片的高度 但是div的宽度小于图片的宽度

            img.css("height", imgHeight);
            img.css("margin-left", (d / 2) + "px");
            img.css("margin-top", (c / 2) + "px");
        } else if (divHeight < imgHeight && divWidth >= imgWidth) {
            //div的高度小于图片的高度 但是div的宽度大于等于图片的宽度

            img.css("width", imgWidth);
            img.css("margin-left", (d / 2) + "px");
            img.css("margin-top", (c / 2) + "px");
        }
    }

})(jQuery);

$(function () {

    $("div[img-resize='true']").imgresize();
    // $("li[img-resize='true']").imgresize();
});
   
  
 